#ifndef WIFI_CONTROL_H
#define WIFI_CONTROL_H

#include <WiFi.h>
#include <WebServer.h>

// 网络配置
#define WIFI_SSID "MERCURY_77FC"
#define WIFI_PASS "30243024"

// 网页控制界面
const char* CONTROL_PAGE = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>ESP32 Car Control</title>
  <style>
    .control { text-align:center; margin-top:50px; }
    button { width:100px; height:60px; margin:10px; font-size:20px; }
  </style>
</head>
<body>
  <div class="control">
    <h1>ESP32 Car Control</h1>
    <button onclick="control('forward')">↑11</button><br>
    <button onclick="control('left')">←</button>
    <button onclick="control('stop')">STOP</button>
    <button onclick="control('right')">→</button><br>
    <button onclick="control('backward')">↓</button>
  </div>
  <script>
    function control(cmd) {
      fetch('/control?cmd=' + cmd)
        .then(r => r.text())
        .then(t => console.log(t))
        .catch(e => console.error(e));
    }
  </script>
</body>
</html>
)rawliteral";

typedef void (*MotorControlCallback)(const String& cmd);

class WiFiControl {
private:
  WebServer server;
  MotorControlCallback controlCallback;

  void handleRoot() {
    server.send(200, "text/html", CONTROL_PAGE);
  }

  void handleControl() {
    if (server.hasArg("cmd")) {
      String cmd = server.arg("cmd");
      Serial.println("Received: " + cmd);
      if (controlCallback) controlCallback(cmd);
      server.send(200, "text/plain", "OK: " + cmd);
    } else {
      server.send(400, "text/plain", "Bad Request");
    }
  }

public:
  void begin(MotorControlCallback callback) {
    controlCallback = callback;
    
    WiFi.begin(WIFI_SSID, WIFI_PASS);
    Serial.print("Connecting to WiFi...");
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("\nConnected! IP: " + WiFi.localIP().toString());

    server.on("/", std::bind(&WiFiControl::handleRoot, this));
    server.on("/control", std::bind(&WiFiControl::handleControl, this));
    server.begin();
  }

  void update() {
    server.handleClient();
  }
};

#endif